package com.cj.sys.dao.security;

import java.util.Set;

import org.springframework.stereotype.Repository;

import com.cj.common.orm.hibernate.HibernateDao;
import com.cj.sys.entity.security.Authority;
import com.cj.sys.entity.security.Resource;
import com.cj.sys.service.ServiceException;

@Repository
public class ResourceDao extends HibernateDao<Resource, Long> {
	@Override
	public void delete(Resource resource) {
		Set<Resource> children = resource.getChildren();
		for (Resource child : children) {
			delete(child);
		}
		for(Authority authority : resource.getAuthorities()){
			authority.getResources().remove(resource);
		}
		super.delete(resource);
	}
	
	@Override
	public void save(Resource entity) {
		if(entity.getId() != null && entity.getParent() != null && entity.getParent().getId() != null){
			if(entity.getId().equals(entity.getParent().getId()))
				throw new ServiceException("上级菜单不能为自己！");
		}
		super.save(entity);
	}
}
